﻿@using OA.AspNetCore.Html;
@using OA.Model;
@using OA.Core.Model;
@using System.Text
@model List<ExtendField>

@{
    ViewBag.Title = "表格预览";
    Layout = "~/Areas/Admin/Views/Shared/_form_layout.cshtml";
    List<ExtendField> extendFields = Model;
    Queue<string> parentsName = new Queue<string>();
    int index = 0;
    Dictionary<string, int> dicIndex = new Dictionary<string, int>();
    Dictionary<string, int> dicColspan = new Dictionary<string, int>();
    foreach (var item in extendFields)
    {
        if (!parentsName.Contains(item.ParentName))
        {
            parentsName.Enqueue(item.ParentName);
            item.Sort = index;
            dicIndex.Add(item.ParentName, index);
            dicColspan.Add(item.ParentName, 1);
        }
        else
        {
            item.Sort = dicIndex[item.ParentName];
            dicColspan[item.ParentName] += 1;
        }
    }
    extendFields = extendFields.OrderBy(m => m.Sort).ToList();
    var parents = Model.Where(m => !string.IsNullOrWhiteSpace(m.ParentName)).ToList();
    string jsContent = string.Empty;
    List<Dictionary<string, string>> infoTableValues = new List<Dictionary<string, string>>() { new Dictionary<string, string>() };
}
<link rel="stylesheet" type="text/css" href="@ViewBag.OssUrl/front/webuploader/webuploader.css">
<script type="text/javascript" src="@ViewBag.OssUrl/front/webuploader/webuploader.js"></script>
<script type="text/javascript" src="/js/xm-select.js"></script>
<script type="text/javascript" src="/Admin/Home/GetXmSelectPositions"></script>
<script type="text/javascript" src="/Admin/Home/GetXmSelectEmployees"></script>
<script type="text/javascript" src="/Admin/Home/GetXmSelectDepartment"></script>
<div class="layui-form layui-tab-content" style="padding:20px 40px 20px 0;">
    @using (Html.BeginForm(FormMethod.Post, htmlAttributes: new { @class = "layui-form", id = "myForm" }))
    {


        <table class="layui-table">
            <thead>
                @if (Model != null)
                {
                    if (parentsName.Count != extendFields.Count)
                    {
                        <tr>
                            @foreach (var parentName in parentsName)
                            {
                                int children = dicColspan[parentName];
                                if (children == 1)
                                {
                                    <td rowspan="2" style="text-align:center;">@parentName</td>
                                }
                                else
                                {
                                    <td colspan="@children" style="text-align:center;">@parentName</td>
                                }
                            }
                            <td rowspan="2" style="text-align:center;">#</td>
                        </tr>
                    }
                }
                <tr>
                    @foreach (var item in extendFields)
                    {
                        if (parentsName.Count == extendFields.Count || dicColspan[item.ParentName] > 1)
                        {
                            <th> @item.Name </th>
                        }

                        if (item.Type == 69 || item.Type == 68)
                        {
                            if (!string.IsNullOrWhiteSpace(item.Values))
                            {
                                string[] myFields = item.Values.Split(new string[] { "+", "-", "*", "/", "(", ")", "[", "]" }, StringSplitOptions.RemoveEmptyEntries);
                                List<string> fields = new List<string>();
                                string objs = string.Empty;
                                foreach (string key in myFields)
                                {
                                    double temp = 0;
                                    if (!double.TryParse(key, out temp))
                                    {
                                        fields.Add("." + key);
                                        objs += "var " + key + "=parseFloat(trObj.find('." + key + "').val());\r\n";
                                    }
                                }
                                if (fields.Count > 0)
                                {
                                    string objTotal = string.Join(",", fields);
                                    objs += "trObj.find('." + item.Attribute + "').val(Math.formatFloat(" + item.Values + ",2));\r\n";
                                    jsContent += "<script type='text/javascript'>$(document).on('change', '" + objTotal + "', function(){\r\nvar trObj = $(this).parent().parent();\r\n" + objs + "});</script>";

                                }
                            }
                        }
                        else if (item.Type == 3 && !string.IsNullOrWhiteSpace(item.Values) && (item.Values.StartsWith("http://") || item.Values.StartsWith("https://")))
                        {
                            try
                            {
                                System.Net.WebClient wc = new System.Net.WebClient();
                                wc.Encoding = Encoding.UTF8;
                                string result = wc.DownloadString(item.Values);
                                StringBuilder sb = new StringBuilder();
                                sb.Append(@"<script type=""text/javascript"">
                                    var " + item.Attribute + @" = " + result + @";
                                    layui.use('form', function () {
                                                var form = layui.form;
                                                form.on('select(" + item.Attribute + @")', function (data) {
                                                    var trInfo=$(data.elem).parent().parent();
                                                    if($(data.elem).parent().hasClass(""layui-input-block""))
                                                    {

                                                    }
                                                    $.each(" + item.Attribute + @", function (index, info) {
                                                        if (info.Value == data.value) {
                                                            for (var key in info) {
                                                                if (trInfo.find("".""" + @"+key).length > 0) { trInfo.find("".""" + @"+key).val(info[key]); }
                                                            }
                                                        }
                                                    });
                                                });
                                            });
                                        </script>");
                                jsContent = sb.ToString();
                            }
                            catch (Exception ex)
                            {

                            }
                        }
                    }
                    @if (parentsName.Count == extendFields.Count)
                    {
                        <td style="text-align:center;">#</td>
                    }
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < infoTableValues.Count; i++)
                {
                    var valueItem = infoTableValues[i];

                    <tr data-id="@i">
                        @for (int j = 0; j < extendFields.Count; j++)
                        {
                            ExtendField infoExtendField = new ExtendField();
                            infoExtendField = extendFields[j];
                            var cellValue = string.Empty;
                            if (valueItem.ContainsKey(infoExtendField.Attribute))
                            {
                                infoExtendField.Value = valueItem[infoExtendField.Attribute];
                            }
                            else
                            {
                                infoExtendField.Value = infoExtendField.DefaultValue;
                            }
                            <td>
                                @Html.Raw(MvcHtmlExtension.GetMyEditorControl(infoExtendField, "tableValues.RowValues[" + i.ToString() + "].CellValues."))
                            </td>
                        }
                        <td>
                            <input type="hidden" class="Status" value="1" name="tableValues.RowValues[@i].Status" />
                            <span class="layui-btn layui-btn-xs layui-btn-danger deleteItem">删除</span>
                        </td>
                    </tr>
                }
            </tbody>
            <tfoot>
                @{
                    int colspan = Model.Count + 1;
                }
                <tr><td colspan="@colspan" class="right_content"><button type="button" class="layui-btn layui-btn-normal addItem">增加一行</button></td></tr>
            </tfoot>
        </table>

    }
</div>

<script type="text/javascript">
    function InintTable() {
        $(".xm-select-demo").each(function (index, item) {
            if ($(item).html() == "") {
                var base64Info = $(item).attr("data-values");
                var selects = $(item).attr("data-value");
                var tips = $(item).attr("data-tips");
                var my_id = $(item).prop("id");
                var str = Base64.decode(base64Info);
                var list = JSON.parse(str);
                var currentValues = [];
                if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
                var mydata = [];
                $.each(list, function (index, item) {
                    if (currentValues != null && currentValues.length > 0 && currentValues.indexOf(item.Value) > -1) {
                        mydata.push({ name: item.Text, value: item.Value, selected: true });
                    }
                    else {
                        mydata.push({ name: item.Text, value: item.Value, selected: false });
                    }
                });
                xmSelect.render({
                    el: '#' + my_id,
                    tips: tips,
                    data: mydata,
                    model: {
                        label: {
                            type: 'text',
                            block: {
                                showCount: 1,
                                showIcon: false,
                            }
                        }
                    },
                })
            }
        });

        $(".xm-select-department").each(function (index, item) {
            if ($(item).html() == "") {
                var selects = $(item).attr("data-value");
                var currentValues = [];
                if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
                var tips = $(item).attr("data-tips");
                var my_id = $(item).prop("id");
                xmSelect.render({
                    el: '#' + my_id,
                    tips: tips,
                    initValue: currentValues,
                    data: xmSelectDepartment,
                    filterable: true,
                    radio: true,
                    clickClose: true,
                    tree: {
                        show: true,
                        showFolderIcon: true,
                        showLine: true,
                        indent: 20,
                        expandedKeys: true,
                        strict: false
                    },
                    model: {
                        label: {
                            type: 'text',
                            block: {
                                showCount: 1,
                                showIcon: false,
                            }
                        }
                    },
                })
            }
        });

        $(".xm-select-employee").each(function (index, item) {
            if ($(item).html() == "") {
                var selects = $(item).attr("data-value");
                var currentValues = [];
                if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
                var tips = $(item).attr("data-tips");
                var my_id = $(item).prop("id");
                xmSelect.render({
                    el: '#' + my_id,
                    tips: tips,
                    initValue: currentValues,
                    data: xmSelectEmployee,
                    toolbar: { show: true },
                    filterable: true,
                    autoRow: true,
                    radio: true,
                    clickClose: true,
                    tree: {
                        show: true,
                        showFolderIcon: true,
                        showLine: true,
                        indent: 20,
                        expandedKeys: true,
                        strict: true
                    },
                    model: {
                        label: {
                            type: 'text',
                            block: {
                                showCount: 1,
                                showIcon: false,
                            }
                        }
                    },
                })
            }
        });

        $(".xm-select-position").each(function (index, item) {
            if ($(item).html() == "") {
                var selects = $(item).attr("data-value");
                var currentValues = [];
                if (selects != null && selects.length > 0) { currentValues = selects.split(","); }
                var tips = $(item).attr("data-tips");
                var my_id = $(item).prop("id");
                xmSelect.render({
                    el: '#' + my_id,
                    tips: tips,
                    initValue: currentValues,
                    data: xmSelectPositions,
                    toolbar: { show: true },
                    filterable: true,
                    radio: true,
                    clickClose: true,
                    tree: {
                        show: true,
                        showFolderIcon: true,
                        showLine: true,
                        indent: 20,
                        expandedKeys: true,
                        strict: true
                    },
                    model: {
                        label: {
                            type: 'text',
                            block: {
                                showCount: 1,
                                showIcon: false,
                            }
                        }
                    },
                })
            }
        });
    }
    InintTable();
</script>